import { executeSQLParam, queryOne, update, insetOrIgnore } from ".";
import { setStorageLocalFileFolder, setStorageLocalServerPort } from "../plus/store/UserData";
import { isEmpty } from "../util/common";
//获取环境变量
const NODE_ENV = process.env.NODE_ENV;
const userDir = "_doc/"
const updateContactNoReadCount = ({userId, noReadCount}) => {
    return new Promise(async (resolve, _reject) => {
        let sql;
        if(noReadCount == 0){
            console.log("没有新联系人...")
            resolve();
            return;
        }
        if(!isEmpty(noReadCount)){
            sql = "update user_setting set contact_no_read = contact_no_read+? where user_id = ?"
        }else{
            //清空未读数
            noReadCount = 0;
            sql = "update user_setting set contact_no_read = ? where user_id = ?"
        }
        await executeSQLParam(sql, [noReadCount, userId])
        resolve()
    });
}

const addUserSetting = async (userId, emailOrPhone) => {
    console.log('\x1b[32m' + "开始增加用户:"+ userId +"和邮箱或者手机号:"+emailOrPhone+"配置..." + '\x1b[0m')
    let sql = "select max(server_port) server_port from user_setting";
    let {serverPort} = await queryOne(sql, []);
    if(serverPort == null){
        serverPort = 10240;
    } else {
        serverPort++;
    }
    const sysSetting = {
        'localFileFolder' : userDir + (NODE_ENV === 'development' ? ".mychattest/fileStorage/" : ".mychat/fileStorage/")
    }
    sql = "select * from user_setting where user_id = ?";
    const userInfo = await queryOne(sql, [userId]);
    let resultServerPort = null;
    let localFileFolder = sysSetting.localFileFolder + userId;
    if(!isEmpty(userInfo)){
        await update("user_setting", {"email": emailOrPhone}, {"userId": userId});
        resultServerPort = userInfo.serverPort;
        localFileFolder = JSON.parse(userInfo.sysSetting).localFileFolder + userId;
    }else{
        
        await insetOrIgnore("user_setting", {
            userId: userId,
            email: emailOrPhone,
            sysSetting: JSON.stringify(sysSetting),
            contactNoRead: 0,
            serverPort: serverPort
        })
        resultServerPort = serverPort
    }
    //todo 启动本地服务
    setStorageLocalFileFolder(localFileFolder);
    setStorageLocalServerPort(resultServerPort);
}

export{
    updateContactNoReadCount,
    addUserSetting
}